{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hybrid Auto and AStar"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Creates 3 transmon pockets in an L shape, each of which can be rotated in increments of 90 deg.\n",
    "Anchors are user-specified points through which the CPW must pass.\n",
    "For a specified step size and suitable choice of anchors, a snapped path can always be found.\n",
    "How close this path is to the shortest path depends on the step size - a smaller step size generally yields more optimal paths but requires a longer runtime."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next cell enables [module automatic reload](https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html?highlight=autoreload). Your notebook will be able to pick up code updates made to the qiskit-metal (or other) module code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Import key libraries and open the Metal GUI. Also we configure the notebook to enable overwriting of existing components"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from qiskit_metal import designs, draw\n",
    "from qiskit_metal import MetalGUI, Dict\n",
    "\n",
    "design = designs.DesignPlanar()\n",
    "gui = MetalGUI(design)\n",
    "\n",
    "# If you disable the next line, then you will need to delete a component [<component>.delete()] before recreating it.\n",
    "design.overwrite_enabled = True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create 3 transmon qubits with 4 pins. This uses the same definition (options) for all 3 qubits, but it places them in 3 different (x,y) origin points."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket\n",
    "\n",
    "options = dict(\n",
    "    pad_width = '425 um', \n",
    "    pocket_height = '650um',\n",
    "    connection_pads=dict(  # pin connectors\n",
    "        a = dict(loc_W=+1,loc_H=+1), \n",
    "        b = dict(loc_W=-1,loc_H=+1, pad_height='30um'),\n",
    "        c = dict(loc_W=+1,loc_H=-1, pad_width='200um'),\n",
    "        d = dict(loc_W=-1,loc_H=-1, pad_height='50um')\n",
    "    )\n",
    ")\n",
    "\n",
    "q0 = TransmonPocket(design, 'Q0', options = dict(pos_x='-1.0mm', pos_y='-1.0mm', **options))\n",
    "q1 = TransmonPocket(design, 'Q1', options = dict(pos_x='1.0mm', pos_y='+0.0mm', **options))\n",
    "q2 = TransmonPocket(design, 'Q2', options = dict(pos_x='-1.0mm', pos_y='0.0mm', **options))\n",
    "\n",
    "gui.rebuild()\n",
    "gui.autoscale()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Import the RoutePathfinder class and inspect what options are available for you to initialize."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'pin_inputs': {'start_pin': {'component': '', 'pin': ''},\n",
       "  'end_pin': {'component': '', 'pin': ''}},\n",
       " 'fillet': '0',\n",
       " 'lead': {'start_straight': '0mm',\n",
       "  'end_straight': '0mm',\n",
       "  'start_jogged_extension': '',\n",
       "  'end_jogged_extension': ''},\n",
       " 'total_length': '7mm',\n",
       " 'chip': 'main',\n",
       " 'layer': '1',\n",
       " 'trace_width': 'cpw_width',\n",
       " 'anchors': {},\n",
       " 'advanced': {'avoid_collision': 'true'},\n",
       " 'step_size': '0.25mm'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder\n",
    "RoutePathfinder.get_template_options(design)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we've set the fillet radius to be 90 microns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "ops=dict(fillet='90um')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using the 3-qubit arrangement from before, our goal is to connect pins on two of them. Moreover, we want some degree of control over how that path is constructed.\n",
    "This is where anchors come into play. Anchors are predefined points in space that the path must cross. They are stored in an ordered dictionary data structure that maps the\n",
    "anchor number to a numpy array of length 2. The anchor number is an integer, starting at 0, that determines that anchor point's position relative to the start pin; larger\n",
    "anchor numbers are farther along the path. The numpy array stores the x and y coordinates of the anchor.\n",
    "\n",
    "For this and the subsequent examples, we have chosen a step size of 0.25 mm, which means that the algorithm searches for valid paths to the next anchor point in increments\n",
    "of that amount. Valid paths do not collide with other components or self-intersect. The start and end pins are labelled by their component and component-specific pin, in\n",
    "this case Q0_b and Q1_b."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from collections import OrderedDict\n",
    "\n",
    "anchors = OrderedDict()\n",
    "anchors[0] = np.array([0.048, -0.555])\n",
    "anchors[1] = np.array([0.048, 0.195])\n",
    "\n",
    "options = {'pin_inputs': \n",
    "            {'start_pin': {'component': 'Q0', 'pin': 'b'}, \n",
    "             'end_pin': {'component': 'Q1', 'pin': 'b'}},\n",
    "            'lead': {'start_straight': '91um', 'end_straight': '90um'},\n",
    "            'step_size': '0.25mm',\n",
    "            'anchors': anchors,\n",
    "            **ops\n",
    "           }\n",
    "\n",
    "qa = RoutePathfinder(design, 'line', options)\n",
    "\n",
    "gui.rebuild()\n",
    "gui.autoscale()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The current algorithm can only allow 1 such CPW to be built at a time, thus we delete old CPWs before building new ones."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "design.delete_component('line')\n",
    "\n",
    "gui.rebuild()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's try wrapping the CPW around the outer edge of the bottom left qubit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "anchors = OrderedDict()\n",
    "anchors[0] = np.array([-0.452, -0.555])\n",
    "anchors[1] = np.array([-0.452, -1.5])\n",
    "anchors[2] = np.array([0.048, -1.5])\n",
    "\n",
    "options = {'pin_inputs': \n",
    "            {'start_pin': {'component': 'Q0', 'pin': 'b'}, \n",
    "             'end_pin': {'component': 'Q1', 'pin': 'b'}},\n",
    "            'lead': {'start_straight': '91um', 'end_straight': '90um'},\n",
    "            'step_size': '0.25mm',\n",
    "            'anchors': anchors,\n",
    "            **ops\n",
    "           }\n",
    "\n",
    "qa = RoutePathfinder(design, 'line', options)\n",
    "\n",
    "gui.rebuild()\n",
    "gui.autoscale()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "design.delete_component('line')\n",
    "\n",
    "gui.rebuild()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also try switching around the components/pins and not specifying any anchor points to see what happens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "options = {'pin_inputs': \n",
    "            {'start_pin': {'component': 'Q0', 'pin': 'a'}, \n",
    "             'end_pin': {'component': 'Q2', 'pin': 'd'}},\n",
    "            'lead': {'start_straight': '90um', 'end_straight': '90um'},\n",
    "            'step_size': '0.25mm',\n",
    "            **ops\n",
    "          }\n",
    "\n",
    "qa = RoutePathfinder(design, 'line', options)\n",
    "\n",
    "gui.rebuild()\n",
    "gui.autoscale()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "design.delete_component('line')\n",
    "\n",
    "gui.rebuild()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or we can specify even more anchor points!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "anchors = OrderedDict()\n",
    "anchors[0] = np.array([-2, 0.5])\n",
    "anchors[1] = np.array([0, 0.5])\n",
    "anchors[2] = np.array([0, -1])\n",
    "anchors[3] = np.array([2, -1])\n",
    "\n",
    "options = {'pin_inputs': \n",
    "            {'start_pin': {'component': 'Q0', 'pin': 'd'}, \n",
    "             'end_pin': {'component': 'Q1', 'pin': 'c'}},\n",
    "            'step_size': '0.25mm',\n",
    "            'anchors': anchors,\n",
    "            **ops\n",
    "           }\n",
    "\n",
    "qc = RoutePathfinder(design, 'line', options)\n",
    "\n",
    "gui.rebuild()\n",
    "gui.autoscale()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "TODOs:\n",
    "\n",
    "1. CPW bounding boxes are not well-defined and cannot overlap right now. Bounding boxes should occupy as little\n",
    "area as possible to maximize space for other components.\n",
    "    Example: Connecting Q0_a and Q1_b ought to yield an S-shaped CPW but doesn't because there's supposedly a\n",
    "    bounding box with 0 area centered at the origin (0, 0).\n",
    "2. Rebuilding distorts previously well-defined CPWs.\n",
    "    Example: Connect Q0_a, Q1_c, then connect Q1_b and Q0_d.\n",
    "3. Enable anchor revision via the GUI.\n",
    "4. Save a persistent state in the design so that rebuilding doesn't waste time."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
